//
//  MenuView.m
//  HappyRent
//
//  Created by CoderYee on 2017/3/30.
//  Copyright © 2017年 内圈科技. All rights reserved.
//

#import "MenuView.h"
#define kSCREEN_WIDTH   [[UIScreen mainScreen] bounds].size.width
#define kSCREEN_HEIGHT  [[UIScreen mainScreen] bounds].size.height
#define CoverViewAlpha                  0.7

@interface MenuView ()<UIGestureRecognizerDelegate>

@property (nonatomic ,assign)CGRect         menuViewframe;
@property (nonatomic ,assign)CGRect         coverViewframe;
@property (nonatomic ,strong)UIView         *coverView;
@property (nonatomic ,strong)UIView         *rightmenuView;

@end
@implementation MenuView


-(instancetype)initWithDependencyView:(UIView *)dependencyView MenuView:(UIView *)rightmenuView{
    
    if(self = [super init]){
        
        [self addPanGestureAtDependencyView:dependencyView];
        self.rightmenuView = rightmenuView;
        self.coverView.backgroundColor = [UIColor clearColor];
        self.menuViewframe = CGRectMake(kSCREEN_WIDTH-rightmenuView.frame.size.width, rightmenuView.frame.origin.y, rightmenuView.frame.size.width, rightmenuView.frame.size.height);
        self.coverViewframe = CGRectMake(0, self.menuViewframe.origin.y, kSCREEN_WIDTH - self.menuViewframe.size.width, self.menuViewframe.size.height);
    }
    return self;
    
}
-(void)addPanGestureAtDependencyView:(UIView *)dependencyView{
    
    // 屏幕边缘pan手势(优先级高于其他手势)
    UIScreenEdgePanGestureRecognizer *leftEdgeGesture = \
    [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self
                                                      action:@selector(handleLeftEdgeGesture:)];
    leftEdgeGesture.edges                             = UIRectEdgeRight;// 屏幕左侧边缘响应
    leftEdgeGesture.delegate=self;
    [dependencyView addGestureRecognizer:leftEdgeGesture]; //
}


-(void)show{
    
    UIWindow * window = [[UIApplication sharedApplication].delegate window];
    [window addSubview:self.coverView];
    [window addSubview:self.rightmenuView];
    
    self.rightmenuView.frame = CGRectMake(kSCREEN_WIDTH, self.menuViewframe.origin.y, self.menuViewframe.size.width, self.menuViewframe.size.height);
    self.coverView.frame = CGRectMake(0, 0, kSCREEN_WIDTH, self.menuViewframe.size.height);
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.rightmenuView.frame = self.menuViewframe;
        self.coverView.frame    = self.coverViewframe;
        self.coverView.alpha = CoverViewAlpha;
    }];
}
-(void)hidenWithoutAnimation{
    
    [self removeCoverAndMenuView];
}
-(void)hidenWithAnimation{
    
    [self coverTap];
}
#pragma mark - 屏幕左侧菜单
-(UIView *)rightmenuView{
    
    if(_rightmenuView == nil){
        
        UIView *rightView = [[UIView alloc]initWithFrame:self.menuViewframe];
        _rightmenuView    = rightView;
        
    }
    return _rightmenuView;
}


#pragma mark - 遮盖
-(UIView *)coverView {
    
    if (_coverView == nil) {
        
        UIView *Cover = [[UIView alloc]initWithFrame:self.coverViewframe];
        Cover.alpha                               = 0;
        UITapGestureRecognizer *Click             = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(coverTap)];
        [Cover addGestureRecognizer:Click];
        
        UIGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]
                                                     initWithTarget:self
                                                     action:@selector(handleftPan:)];
        
        [Cover addGestureRecognizer:panGestureRecognizer];
        [Click requireGestureRecognizerToFail:panGestureRecognizer];
        _coverView = Cover;
    }
    return _coverView;
}
#pragma mark - 屏幕往右滑处理
- (void)handleLeftEdgeGesture:(UIScreenEdgePanGestureRecognizer *)gesture{
    
    UIWindow * window = [[UIApplication sharedApplication].delegate window];
    [window addSubview:self.coverView];
    [window addSubview:self.rightmenuView];
    // 根据被触摸手势的view计算得出坐标值
    CGPoint translation = [gesture translationInView:gesture.view];
    if(UIGestureRecognizerStateBegan == gesture.state ||
       UIGestureRecognizerStateChanged == gesture.state){
        
        if(ABS(translation.x)+kSCREEN_WIDTH-self.menuViewframe.size.width<=self.rightmenuView.frame.size.width){
            
            if(translation.x >=-10){
                
            self.coverView.frame = CGRectMake(kSCREEN_WIDTH, self.menuViewframe.origin.y, kSCREEN_WIDTH, self.menuViewframe.size.height);
            }
            
            CGFloat x           = translation.x + self.menuViewframe.size.width;
            CGFloat y           = self.menuViewframe.origin.y;
            CGFloat w           = self.menuViewframe.size.width;
            CGFloat h           = self.menuViewframe.size.height;
            self.rightmenuView.frame = CGRectMake(x, y, w, h);
            self.coverView.frame    = CGRectMake(self.rightmenuView.frame.size.width-x, 0,kSCREEN_WIDTH-self.rightmenuView.frame.size.width+x, h);
            self.coverView.alpha    = CoverViewAlpha*(translation.x / w);
            
        }else{
            
            self.rightmenuView.frame = self.menuViewframe;
            self.coverView.frame = self.coverViewframe;
        }
    }
    else{
        
        //结束
        if(ABS(translation.x) > self.menuViewframe.size.width/2){
            // 展开设置
            [self openMenuView];
        }else{
            // 恢复设置
            [self closeMenuView];
        }
        
    }
}

#pragma mark Pan to open/close the drawer
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    UIViewController  *vc=[self getCurrentVC];
    if ([vc isKindOfClass:NSClassFromString(@"TabBarVC")]) {
        //NSLog(@"1%@",NSStringFromClass([vc class]));
        UITabBarController *tabVC=(UITabBarController*)vc;
        UINavigationController *temp = tabVC.selectedViewController;
        if (temp.viewControllers.count>=2 ) {
            return NO;
        }
    }
   // UINavigationController *nv=[self currentNavigationController];
    //NSLog(@"233%@",NSStringFromClass([nv class]));
//    UINavigationController *temp = (UINavigationController *)[self getCurrentVC].navigationController;
//    if (temp.viewControllers.count>=1)
//    {
//        return NO;
//    }
    return YES;
}
#pragma mark - coverView往右滑隐藏
-(void)handleftPan:(UIPanGestureRecognizer*)recognizer{
    
    CGPoint translation = [recognizer translationInView:recognizer.view];
    static CGFloat BeganX;
    
    if(UIGestureRecognizerStateBegan == recognizer.state){
        
        BeganX = translation.x;//记录上一次的位置
    }
    CGFloat Place = (translation.x) - (BeganX);
    

    if(UIGestureRecognizerStateBegan == recognizer.state ||
       UIGestureRecognizerStateChanged == recognizer.state){
        
        CGFloat x           = 0 ;
        CGFloat y           = self.menuViewframe.origin.y;
        CGFloat w           = self.menuViewframe.size.width;
        CGFloat h           = self.menuViewframe.size.height;
        
        if(Place <= self.rightmenuView.frame.size.width &&  Place >0){
            
            x  = kSCREEN_WIDTH-self.menuViewframe.size.width+ Place;
            
            self.coverView.frame    = CGRectMake(Place, 0,kSCREEN_WIDTH-self.rightmenuView.frame.size.width+Place, h);
            self.coverView.alpha    = CoverViewAlpha*((w - Place) / w);
            
        }else if(Place >0){
            
            x  = self.menuViewframe.size.width;
            
            self.coverView.frame    = CGRectMake(0, 0,kSCREEN_WIDTH,h);
            
        }else{
            
            x = kSCREEN_WIDTH-self.rightmenuView.frame.size.width;
            self.coverView.frame    = CGRectMake(0, 0,kSCREEN_WIDTH-self.rightmenuView.frame.size.width, h);
            self.coverView.alpha    = CoverViewAlpha;
        }
        
        self.rightmenuView.frame = CGRectMake(x, y, w, h);
        
        
    }else{
        //结束
        if(Place > self.menuViewframe.size.width/2){
            // 收起设置
            [self closeMenuView];
            
        }else{
            // 展开设置
            [self openMenuView];
        }
    }
    
}


-(void)openMenuView{
    
    [UIView animateWithDuration:0.3 animations:^{
        CGFloat y           = self.menuViewframe.origin.y;
        CGFloat w           = self.menuViewframe.size.width;
        CGFloat h           = self.menuViewframe.size.height;
        self.rightmenuView.frame = CGRectMake(kSCREEN_WIDTH-w, y, w, h);
        self.coverView.frame    = self.coverViewframe;
        self.coverView.alpha    = CoverViewAlpha;
    }];
}

-(void)closeMenuView{
    
    [UIView animateWithDuration:0.3 animations:^{
        
        CGFloat y           = self.menuViewframe.origin.y;
        CGFloat w           = self.menuViewframe.size.width;
        CGFloat h           = self.menuViewframe.size.height;
        self.rightmenuView.frame = CGRectMake(2*kSCREEN_WIDTH-w, y, w, h);//self.LeftViewFrame;
        self.coverView.frame    = CGRectMake(kSCREEN_WIDTH, 0,kSCREEN_WIDTH, self.menuViewframe.size.height);
        
    } completion:^(BOOL finished) {
        
        [self removeCoverAndMenuView];
    }];
}
#pragma mark - 点击遮盖移除
-(void)coverTap{
    
    [UIView animateKeyframesWithDuration:0.3 delay:0 options:UIViewKeyframeAnimationOptionLayoutSubviews animations:^{
        
        self.rightmenuView.frame = CGRectMake(kSCREEN_WIDTH, self.menuViewframe.origin.y, self.menuViewframe.size.width, self.menuViewframe.size.height);
        [self.coverView removeFromSuperview];
    } completion:^(BOOL finished) {
        
        [self.rightmenuView removeFromSuperview];
        
    }];
    
}
#pragma mark - 移除菜单和遮盖
-(void)removeCoverAndMenuView{
    
    self.rightmenuView.frame = CGRectMake(kSCREEN_WIDTH-self.rightmenuView.frame.size.width, 0, self.rightmenuView.frame.size.width, kSCREEN_HEIGHT);
    self.coverView.frame    = CGRectMake(kSCREEN_WIDTH, 0,kSCREEN_WIDTH, kSCREEN_HEIGHT);
    self.coverView.alpha    = 0.0;
    
    [self.coverView removeFromSuperview];
    [self.rightmenuView removeFromSuperview];
}
- (UINavigationController *)currentNavigationController
{
    return [self getCurrentVC].navigationController;
}
//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

+ (UIViewController *)getCurrentVc
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}


@end
